package cn.mymall.web.controller;

import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.City;
import cn.mymall.entity.Member;
import cn.mymall.entity.MemberAddress;
import cn.mymall.entity.Province;
import cn.mymall.service.ICityService;
import cn.mymall.service.ICountyService;
import cn.mymall.service.IMemberAddressService;
import cn.mymall.service.IProvinceService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.DateUtil;
import cn.mymall.util.RegexUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class MemberAddressController extends BaseController{
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private ICountyService countyService;
    @Autowired
    private IProvinceService provinceService;
    @RequestMapping("/home/express/address/save")
    @ResponseBody
    public ResultCode addExpressAddress(Long addressId, String realName, String mobile,
                                        Integer provinceId, Integer citycode, Integer countycode,
                                        String address, String defaultAddress) {
        if (StringUtils.isBlank(realName) || StringUtils.isBlank(mobile)
                || provinceId==null || citycode==null
                || StringUtils.isBlank(address)) {
            return ResultCode.getFailure("缺少参数");
        }
        if(realName.length() > 20) {
            return ResultCode.getFailure("姓名长度不能超过20个字");
        }
        if(!RegexUtil.isMobile(mobile)) {
            return ResultCode.getFailure("手机号格式不正确");
        }
        Member member = getLoginMember();
        if(member==null){
            return ResultCode.getFailure("用户未登录");
        }
        Integer memberId = member.getId();
        MemberAddress memberAddress = null;
        if (addressId == null) {
            memberAddress = new MemberAddress();
        } else {
            memberAddress = memberAddressService.getById(addressId);
            if (memberAddress == null) {
                return ResultCode.getFailure("地址不正确");
            }
            if(!memberAddress.getMemberId().equals(member.getId())){
                return ResultCode.getFailure("非法操作");
            }
        }
        Province province = provinceService.getById(provinceId);
        if (province == null) {
            return ResultCode.getFailure("省份不存在");
        }
        City city = cityService.getByCityCode(citycode);
        if (city == null) {
            return ResultCode.getFailure("城市不存在");
        }
        memberAddress.setRealName(realName);
        memberAddress.setMemberId(memberId);
        memberAddress.setMobile(mobile);
        memberAddress.setProvinceId(provinceId);
        memberAddress.setProvincename(province.getName());
        memberAddress.setCitycode(citycode);
        memberAddress.setCityname(city.getName());
        memberAddress.setAddress(address);
        if(addressId==null){
            memberAddress.setAddTime(DateUtil.getCurFullTimestamp());
        }
        memberAddress.setDefaultAddress((StringUtils.equalsIgnoreCase(defaultAddress, StatusConstant.Y))? StatusConstant.Y:StatusConstant.N);
        memberAddressService.saveOrUpdate(memberAddress);
        if(StringUtils.equals(memberAddress.getDefaultAddress(),StatusConstant.Y)) {
            //重置之前默认地址，重新设置新的默认地址
            jdbcTemplate.update("update member_address set default_address=? where member_id=? and id!=?", StatusConstant.N, member.getId(), memberAddress.getId());
        }
        return ResultCode.getSuccessReturn(memberAddress.getId());
    }

    @RequestMapping("/home/express/address/setDefault")
    @ResponseBody
    public ResultCode setDefault(Integer addressId, String defaultAddress) {
        Member member = getLoginMember();
        MemberAddress memberAddress = memberAddressService.getById(addressId);
        memberAddress.setDefaultAddress(defaultAddress);
        memberAddressService.updateById(memberAddress);
        jdbcTemplate.update("update member_address set default_address=? where member_id=? and id!=?", StatusConstant.N, member.getId(), addressId);
        return ResultCode.SUCCESS;
    }
    @RequestMapping("/home/express/address/get")
    public String getExpressAddress(Integer addressId, ModelMap model){
        List<Province> provinceList = provinceService.list();
        model.put("provinceList", provinceList);
        if(addressId == null) {
            return "front/home/address-modify.ftl";
        }
        Member member = getLoginMember();
        MemberAddress memberAddress = memberAddressService.getById(addressId);
        if (memberAddress == null) {
            return "front/home/address-modify.ftl";
        }
        if(!memberAddress.getMemberId().equals(member.getId())){
            return "front/home/address-modify.ftl";
        }
        model.put("memberAddress", memberAddress);
        return "front/home/address-modify.ftl";
    }
    @RequestMapping("/cityList")
    @ResponseBody
    public ResultCode cityList(Integer provinceId){
        List<City> cityList = cityService.list(new QueryWrapper<City>().eq("province_id", provinceId));
        return ResultCode.getSuccessReturn(cityList);
    }
    @RequestMapping("/home/express/address/del")
    @ResponseBody
    public ResultCode delExpressAddress(Integer addressId){
        if(addressId == null) {
            return ResultCode.getFailure("缺少参数");
        }
        Member member = getLoginMember();
        if(member==null){
            return ResultCode.getFailure("用户未登录");
        }
        MemberAddress memberAddress = memberAddressService.getById(addressId);
        if (memberAddress == null) {
            return ResultCode.getFailure("地址不正确");
        }
        if(!memberAddress.getMemberId().equals(member.getId())){
            return ResultCode.getFailure("非法操作");
        }
        memberAddressService.removeById(addressId);
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/home/express/address/list")
    public String addressList(ModelMap model) {
        Member member = getLoginMember();
        List<MemberAddress> addressList = memberAddressService.list(new QueryWrapper<MemberAddress>().eq("member_id", member.getId()).orderByDesc("id"));
        model.put("memberAddressList", addressList);
        return "front/home/address.ftl";
    }
}
